<template>
  <div class="invitation-container">
    <!-- 标题和操作按钮 -->
    <div class="header">
      <div class="title">
        <el-icon><Promotion /></el-icon>
        <h2>邀请管理</h2>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <div class="form-item-group">
          <el-form-item label="邀请码">
            <el-input
                v-model="searchForm.invitationCode"
                placeholder="请输入邀请码"
                clearable
            />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input
                v-model="searchForm.customersName"
                placeholder="请输入用户名"
                clearable
            />
          </el-form-item>
          <el-form-item label="电话号码">
            <el-input
                v-model="searchForm.phoneNumber"
                placeholder="请输入电话号码"
                clearable
            />
          </el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </div>
        <div class="button-group">
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
          @sort-change="handleSortChange"
      >
        <el-table-column prop="invitationCode" label="邀请码" show-overflow-tooltip />
        <el-table-column prop="customersName" label="用户名" show-overflow-tooltip />
        <el-table-column prop="phoneNumber" label="电话号码" width="120" />
        <el-table-column prop="invitedUsers" label="被邀请人" show-overflow-tooltip />
        <el-table-column prop="invitationIncome" label="邀请收益" width="120">
          <template #default="scope">
            <span class="income">{{ formatMoney(scope.row.invitationIncome) }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="creationTime"
            label="创建时间"
            width="160"
            sortable="custom"
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.creationTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-popconfirm
                title="确认删除该记录吗？"
                @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button type="danger" link>
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="邀请详情"
        width="900px"
        destroy-on-close
    >
      <el-descriptions :column="3" border>
        <el-descriptions-item label="邀请码">
          {{ detailData.invitationInfo?.invitationCode }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ detailData.invitationInfo?.customersName }}
        </el-descriptions-item>
        <el-descriptions-item label="电话号码">
          {{ detailData.invitationInfo?.phoneNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="总收益">
          <span class="income">{{ formatMoney(detailData.totalIncome) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="邀请好友数">
          <el-badge :value="detailData.totalFriends" type="primary">
            {{ detailData.totalFriends }}
          </el-badge>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(detailData.invitationInfo?.creationTime) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 好友列表 -->
      <div class="detail-section">
        <div class="section-header">
          <h3>邀请好友列表</h3>
          <el-tag type="info">共 {{ detailData.totalFriends }} 人</el-tag>
        </div>
        <el-table :data="detailData.friendList" border stripe height="250">
          <el-table-column prop="friendName" label="好友姓名" />
          <el-table-column prop="friendPhone" label="好友电话" />
          <el-table-column prop="registerTime" label="注册时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.registerTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                {{ scope.row.status === 1 ? '已注册' : '未注册' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 收益明细 -->
      <div class="detail-section">
        <div class="section-header">
          <h3>收益明细</h3>
          <el-tag type="success">总收益: {{ formatMoney(detailData.totalIncome) }}</el-tag>
        </div>
        <el-table :data="detailData.incomeDetails" border stripe height="250">
          <el-table-column prop="incomeAmount" label="收益金额">
            <template #default="scope">
              <span class="income">{{ formatMoney(scope.row.incomeAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="incomeType" label="收益类型">
            <template #default="scope">
              <el-tag :type="getIncomeTypeTag(scope.row.incomeType)">
                {{ getIncomeTypeName(scope.row.incomeType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="incomeTime" label="收益时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.incomeTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {
  View,
  Delete,
  Search,
  Refresh,
  Promotion
} from '@element-plus/icons-vue'
import axios from 'axios'

// 搜索表单数据
const searchForm = reactive({
  invitationCode: '',
  customersName: '',
  phoneNumber: '',
  status: '',
  invitationType: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 详情对话框相关
const dialogVisible = ref(false)
const detailData = ref({})

// 获取表格数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/invitationInfo/list', {
      params: {
        ...searchForm,
        current: pagination.current,
        size: pagination.size
      }
    })
    tableData.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const response = await axios.get(`/invitationInfo/detail/${row.id}`)
    detailData.value = response.data
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await axios.delete(`/invitationInfo/remove/${row.id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 排序处理
const handleSortChange = ({prop, order}) => {
  if (prop === 'creationTime') {
    searchForm.orderBy = order === 'ascending' ? 'asc' : 'desc'
    fetchData()
  }
}

// 工具函数
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const formatMoney = (amount) => {
  if (!amount) return '¥0.00'
  return `¥${Number(amount).toFixed(2)}`
}

const getIncomeTypeName = (type) => {
  const typeMap = {
    1: '注册收益',
    2: '充值收益',
    3: '消费收益'
  }
  return typeMap[type] || '其他收益'
}

const getIncomeTypeTag = (type) => {
  const tagMap = {
    1: 'success',
    2: 'primary',
    3: 'warning'
  }
  return tagMap[type] || 'info'
}

// 搜索和重置
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => searchForm[key] = '')
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.size = val
  fetchData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  fetchData()
}

// 页面加载
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
/* 容器基础样式 */
.invitation-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

/* 头部样式 */
.header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header .title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header .title h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

/* 搜索区域样式 */
.search-container {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-item-group {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  flex: 1;
}

.button-group {
  display: flex;
  gap: 8px;
  align-items: center;
  white-space: nowrap;
}

/* 表格区域样式 */
.table-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 详情区域样式 */
.detail-section {
  margin-top: 24px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  padding: 16px 24px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #EBEEF5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 金额样式 */
.income {
  color: #67c23a;
  font-weight: 500;
}

/* 分页区域样式 */
.pagination {
  margin-top: 24px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #dcdfe6;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .form-item-group {
    flex-direction: column;
    width: 100%;
  }

  .button-group {
    width: 100%;
    justify-content: flex-end;
    margin-top: 16px;
  }

  :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}

/* 通用样式调整 */
:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 0;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style>